package com.gin.common.util;

import okhttp3.*;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * create  on 2020-01-06 16:55
 */
public class OkHttpUtil {

    private static final Logger logger = LoggerFactory.getLogger(OkHttpUtil.class);


    private static OkHttpClient client;

    private static final String DEFAULT_MEDIA_TYPE = "application/json; charset=utf-8";

    private static final int CONNECT_TIMEOUT = 5;

    private static final int READ_TIMEOUT = 15;

    private static final String USER_MESSAGE = "userMessage";

    private static final String DEVELOPER_MESSAGE = "developerMessage";

    private static final String GET = "GET";

    private static final String POST = "POST";

    /**
     * 单例模式  获取类实例
     *
     * @return client
     */
    private static OkHttpClient getInstance() {
        if (client == null) {
            synchronized (OkHttpClient.class) {
                if (client == null) {
                    client = new OkHttpClient.Builder()
                            .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                            .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                            .build();
                }
            }
        }
        return client;
    }

    /**
     * get 请求
     *
     * @param url     地址带参数
     * @param headers
     * @return
     */
    public static String doGetBase(String url, Map<String, String> headers) {
        try {
            logger.info("get url ={}, header = {}", url, headers);
            Request.Builder builder = new Request.Builder().url(url);
            if (MapUtils.isNotEmpty(headers)) {
                for (String key : headers.keySet()) {
                    builder.addHeader(key, headers.get(key));
                }
            }
            Request request = builder.build();

            // 创建一个请求
            Response response = getInstance().newCall(request).execute();
            return response.body().string();
        } catch (Exception ex) {
            logger.error("", ex);
            return StringUtils.EMPTY;
        }
    }

    /**
     * post 请求
     *
     * @param url
     * @param headers
     * @param param
     * @return
     */
    public static String doPostBase(String url, Map<String, String> headers, Map<String, String> param) {
        try {
            logger.info("post url ={}, header = {}", url, headers);
            FormBody.Builder requestBody = new FormBody.Builder();  // 参数
            if (MapUtils.isNotEmpty(param)) {
                for (String key : param.keySet()) {
                    requestBody.add(key, param.get(key));
                }
            }
            // post
            Request.Builder builder = new Request.Builder().url(url).post(requestBody.build());
            if (MapUtils.isNotEmpty(headers)) {
                for (String key : headers.keySet()) {  // header
                    builder.addHeader(key, headers.get(key));
                }
            }
            // 创建一个请求
            Response response = getInstance().newCall(builder.build()).execute();
            return response.body().string();
        } catch (Exception ex) {
            logger.error("", ex);
            return StringUtils.EMPTY;
        }
    }

    /**
     * post body 请求
     *
     * @param url     地址
     * @param headers 头
     * @param bodyStr 请求body 字符串
     * @return
     */
    public static String doRequestBodyBase(String url, Map<String, String> headers, String bodyStr) {
        try {
            logger.info("post url ={}, header = {},request body = {}.", url, headers, bodyStr);
            RequestBody requestBody = RequestBody.create(MediaType.parse(DEFAULT_MEDIA_TYPE), bodyStr);
            // post
            Request.Builder builder = new Request.Builder().url(url).post(requestBody);
            if (MapUtils.isNotEmpty(headers)) {
                for (String key : headers.keySet()) {  // header
                    builder.addHeader(key, headers.get(key));
                }
            }
            // 创建一个请求
            Response response = getInstance().newCall(builder.build()).execute();
            return response.body().string();
        } catch (Exception ex) {
            logger.error("", ex);
            return StringUtils.EMPTY;
        }
    }

    /**
     * post 请求
     *
     * @param url
     * @param param
     * @return
     */
    public static String doPost(String url, Map<String, String> param) {
        return OkHttpUtil.doPostBase(url, null, param);
    }

    /**
     * get请求
     *
     * @param url    url
     * @param params 参数
     * @return
     */
    public static String doGet(String url, Map<String, String> params) {
        if (MapUtils.isNotEmpty(params)) {
            url += "?";
            for (String key : params.keySet()) {
                url += key + "=" + params.get(key) + "&";
            }
        }
        return OkHttpUtil.doGetBase(url, null);
    }

    /**
     * request body post
     *
     * @param url     地址
     * @param bodyStr 请求body 字符串
     * @return
     */
    public static String doRequestBody(String url, String bodyStr) {
        return OkHttpUtil.doRequestBodyBase(url, null, bodyStr);
    }


    public static void main(String args[]) {
       /* Map<String, String> header = new HashMap<>();
        header.put("Authorization", "APPCODE 0ab99559560e443c8dddf25a90855ffc");
        String data = doGet("https://ali-weather.showapi.com/phone-post-code-weeather?need3HourForcast=0&needAlarm=0&needHourData=0&needIndex=0&needMoreDay=0&phone_code=010&post_code=100022", header);
        System.out.println(data);
        Map<String, String> param = new HashMap<>();
        //param.put("code", "123");
        String rsData = doPost("http://localhost:9093/api/users/auth/login?code=123", param);
        System.out.println(rsData);*/
    }

}
